<template>
  <a-modal
    :z-index="10000"
    :visible="visible"
    class="large-modal"
    @cancel="$emit('update:visible', false)"
  >
    <template slot="footer">
      <a-button @click="$emit('update:visible', false)">
        关闭
      </a-button>
    </template>
    <div v-loading="loading">
      <a-tabs
        type="card"
        :active-key="activeKey"
        @change="tabChange"
      >
        <a-tab-pane
          v-if="isShow('2') && !baseChangeStatus"
          key="2"
          tab="合同评审（分公司）"
        />
        <a-tab-pane
          v-if="isShow('9') && !baseChangeStatus"
          key="9"
          tab="合同评审（公司）"
        />
        <a-tab-pane
          v-if="isShow('1') && baseChangeStatus"
          key="1"
          tab="合同变更"
        />
        <a-tab-pane
          v-if="isShow('3') && !baseChangeStatus"
          key="3"
          tab="合同评审（汇总）"
        />
        <a-tab-pane
          v-if="isShow('4') && !baseChangeStatus"
          key="4"
          tab="授权申请"
        />
        <a-tab-pane
          v-if="isShow('5')"
          key="5"
          tab="用印申请"
        />
        <a-tab-pane
          v-if="isShow('6') && !baseChangeStatus"
          key="6"
          tab="成本分析表"
        />
        <a-tab-pane
          v-if="isShow('7') && !baseChangeStatus"
          key="7"
          tab="资金策划表"
        />
        <a-tab-pane
          v-if="isShow('8') && !baseChangeStatus"
          key="8"
          tab="重大风险化解措施"
        />
        <a-tab-pane
          v-if="isShow('10') && !baseChangeStatus"
          key="10"
          tab="风险复核"
        />
      </a-tabs>
      <img
        style="width: 100%"
        :src="flowChart"
      >
      <a-table
        :columns="columnApprove"
        :data-source="tableData"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
      </a-table>
    </div>
  </a-modal>
</template>

<script>
import { getCurrentProcess, getFlowChart } from '@/api/process'
import totalPackageContractApi from '@/api/legal/branchContract/totalPackageContract'
import { getOrgEmployeesListBy, getProcessGroupPerson } from '@/api/commons'
import { detail } from '@/api/legal/change'
import { Ellipsis } from '@/components'
import JosnBig from 'json-bigint'

export default {
    name: 'Approval',
    props: {
        id: {
            type: [String, Number],
            default: () => ''
        },
        visible: {
            type: Boolean,
            default: () => false
        },
        activeTab: {
            type: String,
            default: () => ''
        },
        baseBusinessId: {
            type: [String, Number],
            default: () => ''
        },
        baseChangeStatus: {
            type: [String, Number],
            default: () => ''
        }
    },
    data() {
        return {
            columnApprove: [
                {
                    title: '序号',
                    dataIndex: 'serial',
                    scopedSlots: { customRender: 'serial' },
                    width: 80
                },
                {
                    title: '节点名称',
                    dataIndex: 'taskName'
                },
                {
                    title: '处理人',
                    dataIndex: 'userName',
                    ellipsis: true
                },
                {
                    title: '审批意见',
                    dataIndex: 'opinions',
                    ellipsis: true
                },
                {
                    title: '开始时间',
                    dataIndex: 'createTime'
                },
                {
                    title: '滞留时间',
                    dataIndex: 'durationInMillis'
                },
                {
                    title: '结束时间',
                    dataIndex: 'endTime'
                }
            ],
            tableData: [],
            activeKey: '2',
            loading: false,
            flowChart: ''
        }
    },
    created() {},
    watch: {
        async visible(val) {
            if (val) {
                if (this.activeTab) {
                    this.activeKey = this.activeTab
                }
                if (this.baseChangeStatus) {
                    this.activeKey = '1'
                } else {
                    this.activeKey = '2'
                }
                this.loading = true
                await this.getFlowChart(this.id)
                await this.getTableData(this.id)
                this.loading = false
            } else {
                this.tableData = []
                this.flowChart = ''
                this.activeKey = '2'
                this.$emit('update:activeTab', null)
            }
        }
    },
    methods: {
        isShow(key) {
            if (this.activeTab) {
                return key === this.activeTab
            }
            return true
        },
        async getFlowChart(id) {
            let res = await getFlowChart(id)
            if (res.code === 200) {
                this.flowChart = 'data:image/png;base64,' + res.data
            }
        },
        async getTableData(id) {
            return getCurrentProcess(id).then((res) => {
                const processData = res.data
                const userIds = []
                const groupList = []
                processData.forEach((item) => {
                    userIds.push(item.assignee)
                    item.userName = item.userName || ''
                    item.endTime = item.endTime || (item.completed !== 2 && '进行中') || ''
                    item.durationInMillis = item.durationInMillis || (item.completed !== 2 && '进行中') || ''
                    if (item.formData) {
                        try {
                            const formDataObj = JosnBig.parse(item.formData)
                            item.opinions = formDataObj.opinions
                            item.auditResult =
                                formDataObj.reject === 'true'
                                    ? '审批不通过'
                                    : formDataObj.reject === 'false'
                                    ? '审批通过'
                                    : ''
                        } catch (e) {
                            console.error(e)
                        }
                    } else {
                        item.opinions = ''
                        item.auditResult = ''
                    }
                    // 如果groupId存在，则需要查询其节点对应的处理人；completed为1时，表示审批已完成
                    if (item.groupId && item.completed !== 1) {
                        try {
                            const groupIdObj = JosnBig.parse(item.groupId)
                            groupList.push({ ...groupIdObj, processTaskId: item.taskDefKey })
                        } catch (e) {
                            console.error(e)
                        }
                    }

                    item.description = []
                })
                // 获取后面节点的处理人列表
                groupList.length &&
                    getProcessGroupPerson({
                        assignGroup: groupList
                    }).then((res) => {
                        const targetObj = res.data || {}
                        processData.forEach((item) => {
                            if (targetObj[item.taskDefKey] && item.groupId && item.completed !== 1) {
                                item.userName = targetObj[item.taskDefKey].map((item) => item.name).join('、')
                            }
                        })
                    })
                getOrgEmployeesListBy({ userIds, delete: true }).then((employees) => {
                    this.flowRequesting = false
                    processData.forEach((r) => {
                        employees.data.some((e) => {
                            if (e.userId === r.assignee) {
                                r.userName = e.name
                                return true
                            }
                        })
                    })
                    this.tableData = res.data
                })
            })
        },
        async tabChange(key) {
            this.flowChart = ''
            this.tableData = []
            this.loading = true
            this.activeKey = key
            let res
            let id
            switch (key) {
                case '2':
                    await this.getFlowChart(this.id)
                    await this.getTableData(this.id)
                    break
                case '9':
                    await this.getFlowChart(this.baseBusinessId)
                    await this.getTableData(this.baseBusinessId)
                    //    res = await totalPackageContractApi.finComAuditInfoByBaseId({}, { edit: true, baseId: this.baseBusinessId })
                    break
                case '3':
                    res = await totalPackageContractApi.findComReviewByBaseId({}, { edit: true, baseId: this.id })
                    break
                case '4':
                    res = await totalPackageContractApi.findApplyForAuthorityByBaseId(
                        {},
                        { edit: true, baseId: this.id }
                    )
                    break
                case '5':
                    res = await totalPackageContractApi.findApplyForSealByBaseId({}, { edit: true, baseId: this.id })
                    break
                case '6':
                    res = await totalPackageContractApi.findGeneralContractCostAnalysisByBaseId(
                        {},
                        { edit: true, baseId: this.id }
                    )
                    break
                case '7':
                    res = await totalPackageContractApi.findProjectFundPlanTableByBaseId(
                        {},
                        { edit: true, baseId: this.id }
                    )
                    break
                case '8':
                    res = await totalPackageContractApi.findMajorRisksByBaseId({}, { edit: true, baseId: this.id })
                    break
                case '10':
                  res = await totalPackageContractApi.findDangerReviewByBaseId({}, { id: this.id })
                    break
                case '1':
                    res = await detail({ id: this.id })
                    break
            }
            if (res && res.code === 200) {
                  if(key === '10'){
                    id = res.data.id
                  }else if(key === '1'){
                    id = res.data.baseId
                  }else {
                    id = res.data.businessId || res.data.baseBusinessId
                  }
                if (id) {
                    await this.getFlowChart(id)
                    await this.getTableData(id)
                }
            }
            this.loading = false
        }
    }
}
</script>

<style scoped>
</style>
